import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const request = axios.create({
    baseURL: '/api', // 代理前缀
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }

        console.log('发送请求:', config.method?.toUpperCase(), config.url)
        return config
    },
    (error) => {
        console.error('请求配置错误:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    (response) => {
        console.log('请求成功:', response.config.url)
        return response.data
    },
    (error) => {
        console.error('请求失败:', error.config?.url, error.response?.status)

        if (error.response) {
            const status = error.response.status
            const message = error.response.data?.message || '请求失败'

            switch (status) {
                case 401:
                    ElMessage.error('登录已过期，请重新登录')
                    localStorage.removeItem('token')
                    localStorage.removeItem('userInfo')
                    setTimeout(() => {
                        window.location.href = '/login'
                    }, 1500)
                    break
                case 403:
                    ElMessage.error('访问被拒绝，请检查权限')
                    break
                case 404:
                    ElMessage.error('请求的资源不存在')
                    break
                case 500:
                    ElMessage.error('服务器内部错误，请稍后重试')
                    break
                default:
                    ElMessage.error(message)
            }
        } else if (error.code === 'ECONNREFUSED') {
            ElMessage.error('无法连接到服务器，请检查后端服务是否启动')
        } else if (error.request) {
            ElMessage.error('网络错误，请检查网络连接')
        } else {
            ElMessage.error('请求配置错误')
        }

        return Promise.reject(error)
    }
)

export default request